var pageSize = 10;
var limitSettings = {};


// 分页事件
/*
* @param isPersonFirst slider 人 这里第一个被复制了3次
* */
function changePage(settings, tableClassName, tableIndex, configInfo) {

  settings.oFeatures.bProcessing = true
  settings.oApi._fnProcessingDisplay(settings, true)
  var configInfo = configInfo || houseInfo;
  var tableName = tableClassName.replace('.', '')
  var cacheResponse = configInfo.cacheList[tableName][settings._iDisplayStart]
  if (!cacheResponse) {
    let url = configInfo.ajaxUrl[configInfo.ajaxIndex[tableName]].pageItem(settings._iDisplayStart, 10);
    if (settings._iDisplayStart > 10000) {
      url = configInfo.ajaxUrl[configInfo.ajaxIndex[tableName]].pageItem(settings._iDisplayStart, 10, configInfo.total[configInfo.ajaxIndex[tableName]]);
    }
    $.ajax({
      type: 'GET',
      url: url,
      beforeSend: function (xhr) {
        xhr.setRequestHeader('Authorization', tokenPgAuth);
        xhr.setRequestHeader('Accept-Profile', 'api-ailock-analysis-v1');
      }
    }).done(function (response) {
      response = response || [];
      configInfo.cacheList[tableName][settings._iDisplayStart] = settings._iDisplayStart < 10000 ? response : response.reverse()
      settings.oFeatures.bPaginate = false
      settings.aoData = [];
      for (i = 0; i < response.length; i++) {
        settings.oApi._fnAddData(settings, response[i]);
      }
      settings.oApi._fnProcessingDisplay(settings, false)
      settings.oApi._fnDraw(settings)
      if (tableIndex === 0 || tableIndex === 1) { // 中间的那个slider没有复制节点 不需要 trigger 事件
        let allBtn = $(tableClassName).eq(tableIndex).next().find('.paginate_button');
        allBtn.each(function (idx, it) {
          if ($(it).html() == ((settings._iDisplayStart + 10) / 10)) {
            setTimeout(() => {
              $(it).trigger('click')
            }, 50)
          }
        })
      }
      if (Array.isArray(tableIndex)) {
        var activePageNumber = ((settings._iDisplayStart + 10) / 10);
        var $tableClassName = $(tableClassName)
        tableIndex.forEach(function (itemIndex) {
          let allBtn = $tableClassName.eq(itemIndex).next().find('.paginate_button');
          allBtn.each(function (idx, it) {
            if ($(it).html() == activePageNumber) {
              setTimeout(() => {
                $(it).trigger('click')
              }, 50)
            }
          })
        })
      }
    })
  } else {
    settings.oFeatures.bPaginate = false
    settings.aoData = [];
    if (cacheResponse) {
      for (var i = 0; i < cacheResponse.length; i++) {
        settings.oApi._fnAddData(settings, cacheResponse[i]);
      }
    }
    settings.oApi._fnProcessingDisplay(settings, false)
    settings.oApi._fnDraw(settings)
    if (tableIndex === 0 || tableIndex === 1) {
      let allBtn = $(tableClassName).eq(tableIndex).next().find('.paginate_button');
      allBtn.each(function (idx, it) {
        if ($(it).html() == ((settings._iDisplayStart + 10) / 10)) {
          setTimeout(() => {
            $(it).trigger('click')
          }, 50)
        }
      })
    }
    if (Array.isArray(tableIndex)) {
      var activePageNumber = ((settings._iDisplayStart + 10) / 10);
      var $tableClassName = $(tableClassName)
      tableIndex.forEach(function (itemIndex) {
        let allBtn = $tableClassName.eq(itemIndex).next().find('.paginate_button');
        allBtn.each(function (idx, it) {
          if ($(it).html() == activePageNumber) {
            setTimeout(() => {
              $(it).trigger('click')
            }, 50)
          }
        })
      })
    }
  }
}


var fetch1 = function (pageIndex, callback) {
  pageIndex = pageIndex || 1
  //一房多人居住 manyPeoleInAHouse
  $.ajax({
    type: 'GET',
    url: houseInfo.ajaxUrl[0].page(pageIndex, 10),
    beforeSend: function (xhr) {
      xhr.setRequestHeader('Authorization', tokenPgAuth);
      xhr.setRequestHeader('Accept-Profile', 'api-ailock-analysis-v1');
    }
  }).done(function (response) {
    //一房多人的总数 总数使用在slider里面一个 图标一个 分页处三个地方
    var options = {
      bDestroy: true,
      searching: false,
      bPaginate: false,//表格分页
      bSort: false,
      bLengthMenu: false,
      bInfo: false,
      pageLength: 10, // 每页显示数量
      bAutoWidth: false,
      bLengthChange: false,
      bProcessing: true,
      data: response,
      fnPageChange: function (settings) {
        changePage(settings, '.manyPeoleInAHouseTable', 1)
      },
      columns: [
        {
          data: 'simpleaddr',
          bSortable: false,
          align: 'left',

          render: function (data, type, full, meta) {
            if (!data) data = '--';
            return data
          }
        },
        {
          data: 'housenumber',
          class: 'digit ta',
          bSortable: false,
          render: function (data, type, full, meta) {
            if (!data) data = '--';
            return data
          }
        },
        {
          data: 'stats_per_lock_for_active_formal',  //在住人数
          align: 'left',
          className: 'ta',
          bSortable: false,
          render: function (data, type, full, meta) {
            if (!data) return '--';
            return full.stats_per_lock_for_active_formal.tally_users ? full.stats_per_lock_for_active_formal.tally_users : '--'
          }
        }
      ]
    };
    options.fnInitComplete = function (settings) {
      settings.oFeatures.bPaginate = true;
      if (typeof (callback) === 'function') {
        callback()
      }
      $.ajax({
        type: 'GET',
        url: houseInfo.ajaxUrlTotal[0].page(1, 1),
        beforeSend: function (xhr) {
          xhr.setRequestHeader('Authorization', tokenPgAuth);
          xhr.setRequestHeader('Accept-Profile', 'api-ailock-analysis-v1');
          xhr.setRequestHeader('Prefer', 'count=exact')
        }
      }).done(function (res, type, request1) {

        settings.oFeatures.bProcessing = false;
        houseInfo.total[0] = pgApiUtils.getTotal(request1); // 一房多人的总数
        $('.' + houseInfo.totalDomId[0] + 1).text(houseInfo.total[0])
        $('#' + houseInfo.totalDomId[0] + 2).text(houseInfo.total[0])
        settings._pgAiDisplayLength = houseInfo.total[0]
        settings.oApi._fnAddOptionsHtml(settings)
        settings.oApi._fnDraw(settings)

        var myOptions = jQuery.extend(options, {
          fnPageChange: function (settings) {
            changePage(settings, '.manyPeoleInAHouseTable', 0)
          },
          fnInitComplete: function (settings) {
            settings.oFeatures.bPaginate = true;
            settings._pgAiDisplayLength = houseInfo.total[0]
            settings.oFeatures.bProcessing = false
            settings.oApi._fnAddOptionsHtml(settings)
            settings.oApi._fnDraw(settings)

            houseInfo.bindEvent[0]()
          }
        });
        houseInfo.tables[0][1] = $('.manyPeoleInAHouseTable').eq(1).dataTable(myOptions);
      })

    }

    houseInfo.tables[0][0] = $('.manyPeoleInAHouseTable').eq(0).dataTable(options);

  })
}

houseInfo.bindEvent[0] = function () {
  $(".manyPeoleInAHouseTable").each(function (index, item) {
    $(item).on("click", "tr", function () {//给tr或者td添加click事件
      var data = houseInfo.tables[0][index].api().row(this).data();//获取值的对象数据
      console.log(data);
      getRenterListAndHouseMaster(data)
    })
  })
}
// 房屋总数请求
// $.ajax({
//   type: 'GET',
//    url:pgApiUtils(optimizedBaseUrl + requestApiUrl.LandlordInfo2)
//     .setRequestUrl('select=n_house&')
//     .eqVal('operator_name:'+data.operator_name,'operator_mobile:'+data.operator_mobile),


/*//房东信息   短期没有使用等 也用这个
$.ajax({
  type: 'GET',
  url: pgApiUtils(optimizedBaseUrl + requestApiUrl.LandlordInfo)
    .setRequestUrl('select=house(housenumber,operation(operator_name,operator_mobile,simpleaddr,n_house))&')
    .eqVal('lockid:' + data.lockid)
    .order('lockid'),
  beforeSend: function (xhr) {
    xhr.setRequestHeader('Authorization', tokenPgAuth);
    xhr.setRequestHeader('Accept-Profile', 'api-ailock-analysis-v1');
  }
}).done((res) => {
  console.log('房东信息', res)
}).fail((err) => {
  console.log(err)
})

//房东拥有房间总数（包含不同地址）
$.ajax({
  type: 'GET',
  url: pgApiUtils(optimizedBaseUrl + requestApiUrl.LandlordInfo2)
    .setRequestUrl('select=n_house&')
    .eqVal('operator_name:' + data.operator_name, 'operator_mobile:' + data.operator_mobile),

  beforeSend: function (xhr) {
    xhr.setRequestHeader('Authorization', tokenPgAuth);
    xhr.setRequestHeader('Accept-Profile', 'api-ailock-analysis-v1');
  }
}).done((res) => {
  console.log('房东拥有房间总数（包含不同地址）', res)
}).fail((err) => {
  console.log(err)
})

//  当前入住的人员情况        短期没有使用等也用这个
$.ajax({
  type: 'GET',
  url: pgApiUtils(optimizedBaseUrl + requestApiUrl.CheckInPerson)
    .setRequestUrl('select=valid_from,valid_to,user(name,phone,identifier,headpicture)&userrole=neq.255&keytype=in.(0,2)&keystate=is.true&')
    .eqVal('lockid:' + data.lockid)
    .order('valid_from.desc,valid_to.desc,keyid'),
  beforeSend: function (xhr) {
    xhr.setRequestHeader('Authorization', tokenPgAuth);
    xhr.setRequestHeader('Accept-Profile', 'api-ailock-analysis-v1');
  }
}).done((res) => {
  console.log('当前入住的人员情况', res)
}).fail((err) => {
  console.log(err)
})
// 访客基本情况   点击列表中某一行时，获取该行的 keyid=stats_per_lock_for_informal_last_7day.keys 字 段
$.ajax({
  type: 'GET',
  url: pgApiUtils(optimizedBaseUrl + requestApiUrl.CheckInPerson)
    .setRequestUrl('select=account,valid_from,event_summary(max_opentime),user(key(account))&user.key.userrole=neq.255&user.key.keytype=in.(0,1,2)&user.key.keystate=is.true&keyid=in.(keyid)&')
    .order('valid_from.desc,account'),
  beforeSend: function (xhr) {
    xhr.setRequestHeader('Authorization', tokenPgAuth);
    xhr.setRequestHeader('Accept-Profile', 'api-ailock-analysis-v1');
  }
}).done((res) => {
  console.log('访客基本情况', res)
}).fail((err) => {
  console.log(err)
})

//周期内发放的钥匙情况   获取该行的 keyid=stats_per_lock_for_informal_last_7day.keys 字 段
$.ajax({
  type: 'GET',
  url: pgApiUtils(optimizedBaseUrl + requestApiUrl.CheckInPerson)
    .setRequestUrl('select=keyid,account,valid_from,valid_to,user(name,identifier),event_summary(tally)&keyid=in.(keyid)&')
    .order('valid_from.desc,account'),
  beforeSend: function (xhr) {
    xhr.setRequestHeader('Authorization', tokenPgAuth);
    xhr.setRequestHeader('Accept-Profile', 'api-ailock-analysis-v1');
  }
}).done((res) => {
  console.log('周期内发放的钥匙情况', res)
}).fail((err) => {
  console.log(err)
})



//夜间异常活动--详情页    获取该行 keyid 进行查询
$.ajax({
  type: 'GET',
  url: pgApiUtils(optimizedBaseUrl + requestApiUrl.keyInfoExpect)
    //   .setRequestUrl('select=headpicture,name,phone,identifier,detailaddr,housenumber,tally_per_hour_in_night,tally_per_hour_in_dawn&keyid=eq.cbeadbd3-0d46-4eae-ac45-5cf0874fe42d&'),
   .setRequestUrl('select=headpicture,name,phone,identifier,detailaddr,housenumber,tally_per_hour_in_night,tally_per_hour_in_dawn&keyid=eq.(keyid)&'),
  beforeSend: function (xhr) {
    xhr.setRequestHeader('Authorization', tokenPgAuth);
    xhr.setRequestHeader('Accept-Profile', 'api-ailock-analysis-v1');
  }
}).done((res) => {
  console.log('夜间异常活动--详情页', res)
}).fail((err) => {
  console.log(err)
})
// 住所频繁更换--详情页 获取该行 identifier 进行查询  详情页中“入住房间数”应取 tally_houses 字段
// 最近一次活跃取 key_details 第一行
$.ajax({
  type: 'GET',
  url: pgApiUtils(optimizedBaseUrl + requestApiUrl.personInfo)
    //    .setRequestUrl('select=*&identifier=eq.410781198607213619&'),
     .setRequestUrl('select=*&identifier=eq.(identifier)&'),
  beforeSend: function (xhr) {
    xhr.setRequestHeader('Authorization', tokenPgAuth);
    xhr.setRequestHeader('Accept-Profile', 'api-ailock-analysis-v1');
  }
}).done((res) => {
  console.log('住所频繁更换--详情页', res)
}).fail((err) => {
  console.log(err)
})

// 一人多处住所--详情页    获取该行 identifier 进行查询 “入住房间数”应取 tally_houses 字段
// 最近一次活跃取 key_details 第一行  右侧“入住房间信息”实为“钥匙获取信息”

$.ajax({
  type: 'GET',
  url: pgApiUtils(optimizedBaseUrl + requestApiUrl.moreAddressInfo)
    .setRequestUrl('select=*&identifier=eq.(identifier)&'),
// .setRequestUrl('select=*&identifier=eq.330521198112143631&'),
  beforeSend: function (xhr) {
    xhr.setRequestHeader('Authorization', tokenPgAuth);
    xhr.setRequestHeader('Accept-Profile', 'api-ailock-analysis-v1');
  }
}).done((res) => {
  console.log('一人多处住所--详情页', res)
}).fail((err) => {
  console.log(err)
})*/
